﻿using System;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using System.Drawing;
using System.Net;
using System.Net.Sockets;

namespace LuDo.PitEditor
{
    /// <summary>
    /// Thanks to http://www.codeproject.com/Members/mav-northwind for his RichTextBoxEx control
    /// Internet site: http://www.codeproject.com/KB/edit/RichTextBoxLinks.aspx
    /// </summary>
    public partial class MainForm : Form
    {
        //private string ConnectionString = @"DataSource=C:\Users\Luca\Documents\Visual Studio 2008\Projects\PitEditor\articoli.sdf";
        private string ConnectionString = "";

        private static bool EqualToSpace(char ch)
        {
            if (ch == '\n')
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        private void SetStart()
        {
            editor.Focus();
        }
        private BBCodeWorker CodeWorker { get; set; }
        private bool expandInfo;
        public bool ExpandInfo
        {
            get
            {
                return expandInfo;
            }
            set
            {
                expandInfo = value;
                btnMoreInfo.Image = value ? imageList1.Images[2] : imageList1.Images[1];
                pnlHeader.Height = value ? 285 : 128;
            }
        }
        private void btnMoreInfo_Click(object sender, EventArgs e)
        {
            ExpandInfo = !ExpandInfo;
        }

        public MainForm()
        {
            InitializeComponent();
            LoadProperties();
            ShowNote();
            lblCharsDB.Text = "";
            lblWordsDB.Text = "";
            lblBytesDB.Text = "";
            statusColonna.Text = "";
            statusModificato.Text = "";
            statusRiga.Text = "";
            statusSelez.Text = "";
            itemIcone.Checked = true;
            itemStat.Checked = true;
            itemTesta.Checked = true;
            itemNote.Checked = true;
            itemEditorOnly.Checked = false;
            itemBBCode.Checked = false;
            CodeWorker = new BBCodeWorker(editor);
            ExpandInfo = false;
            articleSize.MaxValue = 10;
            articleSize.Position = 0;
            articleSize.LabelSuffix = "KB";
            articleSize.LabelStep = 2;
            articleSize.GoalValue = 2;
        }

        private void LoadProperties()
        {
            editor.Font = PitEditor.Properties.Settings.Default.EditorFont;
            editor.WordWrap = PitEditor.Properties.Settings.Default.EditorWrapText;
        }

        private void esciToolStripMenuItem_Click(object sender, EventArgs e)
        {
            bool EsistonoModifiche = this.articoliDS.HasChanges();
            if (EsistonoModifiche)
            {
                string testo = String.Format("Sono presenti modifiche. Desideri aggiornare il database ?");
                DialogResult res = MessageBox.Show(testo, "Conferma modifiche", MessageBoxButtons.YesNo);
                if (res == DialogResult.Yes)
                {
                    articoliBindingNavigatorSaveItem_Click(sender, e);
                }
            }
            this.Close();
        }

        #region Gestione StatusBar
        private void ShowNote()
        {
            ShowNote("");
        }
        private void ShowNote(string s)
        {
            statusNote.Text = s == "" ? "Pronto." : s;
        }
        private int CurrentLine
        {
            get
            {
                string text = editor.Text;
                int line = 0;
                if (text != "")
                {
                    int pos = editor.SelectionStart;
                    string substring = text.Substring(0, pos);
                    char[] lineArray = substring.ToCharArray();
                    line = lineArray.Count(c => c == '\n') + 1;
                }
                else
                {
                    line = 1;
                }
                return line;
            }
        }
        private int CurrentPositionInLine
        {
            get
            {
                string text = editor.Text;
                int pos = editor.SelectionStart;
                string substring = text.Substring(0, pos);
                char[] lineArray = substring.ToCharArray();
                char[] reverse = lineArray.Reverse().ToArray();
                int index = Array.FindIndex(reverse, EqualToSpace);
                int position = index == -1 ? reverse.Count() + 1 : index + 1;
                return position;
            }
        }
        private int SelectionLength
        {
            get
            {
                return editor.SelectionLength;
            }
        }
        private void UpdateTitolo()
        {
            DataRowView view = (DataRowView)this.articoliBS.Current;
            if (view != null)
            {
                articoliDS.ArticoliRow row = (articoliDS.ArticoliRow)view.Row;
                this.Text = String.Format("Programmazione.it Editor [{0}]", row.Titolo);
            }
            else
            {
                this.Text = String.Format("Programmazione.it Editor");
            }
        }
        private void UpdateDates()
        {
            DataRowView view = (DataRowView)this.articoliBS.Current;
            if (view != null)
            {
                articoliDS.ArticoliRow row = (articoliDS.ArticoliRow)view.Row;
                btnPrenota.Enabled = !row.Prenotato;
                btnUpload.Text = row.IsDataUploadNull() ? "Conferma pubblicazione" : "Ritira pubblicazione";
                dataUploadLabel.Visible = !row.IsDataUploadNull();
                dateTimePicker2.Visible = !row.IsDataUploadNull();
                dateTimePicker4.Visible = !row.IsDataUploadNull();
            }
        }
        private void UpdateModificato()
        {
            //Relativo a tutta la tabella
            var mod = this.articoliDS.Articoli.GetChanges();
            bool Modificata = mod != null && mod.GetChanges().Rows.Count > 0;
            statusModificato.Text = "";
            statusModificato.Image = Modificata ? imageList1.Images[0] : null;
            statusModificato.ToolTipText = Modificata ? "Dati modificati ma non salvati" : "";
            btnSave.Enabled = Modificata;
            btnRejectChanges.Enabled = Modificata;
            cmdSalvaDB.Enabled = Modificata;
        }
        /// <summary>
        /// Aggiorna i controlli che si riferiscono a linea, colonna e lunghezza selezione.
        /// Dipende dal RichTextBoxEx sulla form.
        /// </summary>
        private void UpdatePos()
        {
            string s = String.Format("Ln {0}", CurrentLine);
            statusRiga.Text = s;
            s = String.Format("Cl {0}", CurrentPositionInLine);
            statusColonna.Text = s;
            s = String.Format("Sel {0}", SelectionLength);
            statusSelez.Text = s;
        }
        /// <summary>
        /// Aggiorna i controlli che visualizzano Numero caratteri, parole, bytes.
        /// Dipende sia dal testo attuale nel txtBBC sia dal campo Testo del record corrente.
        /// </summary>
        #endregion

        #region Menù Database
        private void MainForm_Load(object sender, EventArgs e)
        {
            if (ConnectionString != "")
            {
                this.articoliTA.Connection.ConnectionString = ConnectionString;
            }
            this.articoliTA.Fill(this.articoliDS.Articoli);
            FilterString = Filtering.GeneraFilterString(PitEditor.Properties.Settings.Default.DefaultFilter);
            SortingString = PitEditor.Properties.Settings.Default.DefaultSort;
            articoliBS_CurrentChanged(sender, e);
        }
        private void articoliBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.articoliBS.EndEdit();
            bool RecordAggiunti = this.articoliDS.HasChanges(DataRowState.Added);
            this.articoliTA.Update(this.articoliDS);
            if (RecordAggiunti)
            {
                this.articoliTA.Fill(this.articoliDS.Articoli);
                this.articoliBS.MoveLast();
            }
            UpdateModificato();
        }
        private void btnRejectChanges_Click(object sender, EventArgs e)
        {
            string testo = String.Format("Tutte le modifiche effettuate dall'ultimo salvataggio verranno cancellate. Vuoi procedere?");
            DialogResult res = MessageBox.Show(testo, "Annullamento modifiche", MessageBoxButtons.YesNo);
            if (res == DialogResult.Yes)
            {
                this.articoliDS.Articoli.RejectChanges();
                UpdateModificato();
                this.articoliBS.MoveLast();
            }
        }
        private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e)
        {
            string testo = String.Format("Vuoi davvero cancellare questo articolo. Se accetti non sarà possibile recuperarlo.");
            DialogResult res = MessageBox.Show(testo, "Eliminazione articolo", MessageBoxButtons.YesNo);
            if (res == DialogResult.Yes)
            {
                this.articoliBS.RemoveCurrent();
                UpdateTitolo();
            }
        }
        private void cmdNuovoDB_Click(object sender, EventArgs e)
        {
            articoliDS.ArticoliRow row = articoliDS.Articoli.NewArticoliRow();
            row.DataCreazione = DateTime.Now;
            row.Titolo = "Titolo articolo";
            row.Testo = "Testo articolo";
            row.Prenotato = false;
            this.articoliDS.Articoli.AddArticoliRow(row);

            //Move BindingSource Current to new record
            int minValue = (from articoliDS.ArticoliRow art in this.articoliDS.Articoli.Rows
                            select art.ID).Min();
            int pos = this.articoliBS.Find("ID", minValue);
            this.articoliBS.Position = pos;
        }
        private void articoliBS_CurrentChanged(object sender, EventArgs e)
        {
            CodeWorker.SpellCheckClear();
            DataRowView view = (DataRowView)this.articoliBS.Current;
            pnlHeader.Visible = view != null;
            pnlStat.Visible = view != null;
            EditorArea.Visible = view != null;
            FormatToolstrip.Enabled = view != null;
            bindingNavigatorDeleteItem.Enabled = view != null;
            //cmdSalvaDB.Enabled = view != null;
            //cmdTaglia.Enabled = view != null;
            //cmdCopia.Enabled = view != null;
            //cmdIncolla.Enabled = view != null;
            cmdSort.Enabled = view != null;
            btnSort.Enabled = view != null;
            cmdSelezionaTutto.Enabled = view != null;
            cmdGrassetto.Enabled = view != null;
            cmdCorsivo.Enabled = view != null;
            cmdSottolineato.Enabled = view != null;
            cmdApice.Enabled = view != null;
            cmdBarrato.Enabled = view != null;
            cmdElenco.Enabled = view != null;
            cmdCodice.Enabled = view != null;
            cmdCollegamento.Enabled = view != null;
            cmdFormatReset.Enabled = view != null;
            lblCar.Visible = view != null;
            lblWord.Visible = view != null;
            lblDim.Visible = view != null;
            lblStat.Text = view != null ? "Statistiche articolo" : "Nessun articolo disponibile";
            UpdateTitolo();
            if (view != null)
            {
                UpdateDates();
                UpdateRTF();
                SetStart();
            }
            UpdateModificato();
            ShowNote("");
        }
        private void articoliBS_ListChanged(object sender, ListChangedEventArgs e)
        {
            UpdateModificato();
        }
        private void btnPrenota_Click(object sender, EventArgs e)
        {
            //QUI PRENOTAZIONE VIA MAIL DEGLI ARGOMENTI
            DataRowView view = (DataRowView)this.articoliBS.Current;
            if (view != null)
            {
                articoliDS.ArticoliRow row = (articoliDS.ArticoliRow)view.Row;
                if (row.IsTitoloNull() || row.Titolo == "" || row.IsFontiNull() || row.Fonti == "")
                {
                    MessageBox.Show("Impossibile effettuare la prenotazione: Titolo e/o Fonti articolo sono assenti.");
                }
                else
                {
                    this.Cursor = Cursors.WaitCursor;
                    string body = String.Format("{0}\r\n{1}", row.Fonti, PitEditor.Properties.Settings.Default.SmtpSignature);

                    Mailer mailer = new Mailer(row.Titolo, body);
                    DialogResult rst = mailer.ShowDialog();
                    this.Cursor = Cursors.Default;
                    if (rst == DialogResult.OK)
                    {
                        row.BeginEdit();
                        row.Prenotato = true;
                        row.EndEdit();
                        UpdateDates();
                    }
                    else
                    {
                        MessageBox.Show("Errore invio messaggio.\r\nControllare i parametri della posta nelle Opzioni.");
                    }
                }
            }
        }
        private void btnUpload_Click(object sender, EventArgs e)
        {
            DataRowView view = (DataRowView)this.articoliBS.Current;
            if (view != null)
            {
                articoliDS.ArticoliRow row = (articoliDS.ArticoliRow)view.Row;
                string conferma = row.IsDataUploadNull() ? "Desideri registrare la pubblicazione di questo articolo?"
                    : "Desideri cancellare la pubblicazione di questo articolo?";
                DialogResult rst = MessageBox.Show(conferma, "Richiesta conferma", MessageBoxButtons.YesNo);
                if (rst == DialogResult.Yes)
                {
                    row.BeginEdit();

                    if (row.IsDataUploadNull())
                    {
                        //QUI EVENTUALE OPERAZIONE DI UPLOAD DELL'ARTICOLO SUL SERVER PROGRAMMAZIONE.IT
                        row.DataUpload = DateTime.Now;
                    }
                    else
                    {
                        row.SetDataUploadNull();
                    }
                    row.EndEdit();
                    UpdateDates();
                }
            }
        }
        private void cmdFind_Click(object sender, EventArgs e)
        {
            Finder find = new Finder(this.articoliTA.Connection.ConnectionString, FilterString, SortingString);
            DialogResult res = find.ShowDialog();
            if (res == DialogResult.OK)
            {
                int pos = articoliBS.Find("ID", find.ArticleID);
                articoliBS.Position = pos;
            }
        }
        private string FilterString
        {
            get
            {
                return articoliBS.Filter;
            }
            set
            {
                try
                {
                    articoliBS.Filter = value;
                    btnFilter.ToolTipText = String.Format("Scegli filtro\r\nFiltro attuale: {0}", Filtering.ExplainFilter(value));
                    articoliBS.MoveLast();
                }
                catch
                {
                    MessageBox.Show("Filtro errato!");
                }
            }
        }
        private string SortingString
        {
            get
            {
                return articoliBS.Sort;
            }
            set
            {
                try
                {
                    articoliBS.Sort = value;
                    btnSort.ToolTipText = String.Format("Scegli ordinamento\r\nOrdinamento attuale: {0}", Sorting.ExplainSort(value));
                    articoliBS.MoveLast();
                }
                catch
                {
                    MessageBox.Show("Ordinamento errato!");
                }
            }
        }
        private void btnSort_Click(object sender, EventArgs e)
        {
            Sorting sort = new Sorting(SortingString);
            DialogResult res = sort.ShowDialog();
            if (res == DialogResult.OK)
            {
                SortingString = sort.SortingString;
            }
        }
        private void btnFilter_Click(object sender, EventArgs e)
        {
            Filtering filter = new Filtering(this.FilterString);
            DialogResult res = filter.ShowDialog();
            if (res == DialogResult.OK)
            {
                FilterString = filter.FilteringString;
                string filt = Filtering.ExplainFilter(FilterString);
                bool BozzeShown = filt.Contains("Bozze") || filt.Contains("bozze");
                cmdNuovoDB.Enabled = BozzeShown;
                bindingNavigatorAddNewItem.Enabled = BozzeShown;
            }
        }
        #endregion

        #region Menù Modifica
        private void cmdTaglia_Click(object sender, EventArgs e)
        {
            if (editor.Focused)
            {
                DataRowView view = (DataRowView)this.articoliBS.Current;
                if (view != null)
                {
                    articoliDS.ArticoliRow row = (articoliDS.ArticoliRow)view.Row;
                    try
                    {
                        string text = CodeWorker.GetSelectedText(false);
                        Clipboard.SetText(text);
                        CodeWorker.HandleCancel();

                        row.BeginEdit();
                        row.Testo = CodeWorker.GetBBCode();
                        row.EndEdit();
                        editor.Cut();
                    }
                    catch (ApplicationException)
                    {

                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Errore sconosciuto", MessageBoxButtons.OK);
                    }
                }
            }
            else if (titoloTextBox.Focused)
            {
                titoloTextBox.Cut();
            }
            else if (txtFonti.Focused)
            {
                txtFonti.Cut();
            }
            else if (txtTag.Focused)
            {
                txtTag.Cut();
            }
        }
        private void cmdCopia_Click(object sender, EventArgs e)
        {
            if (editor.Focused)
            {
                string text = CodeWorker.GetSelectedText(false);
                Clipboard.SetText(text);
            }
            else if (titoloTextBox.Focused)
            {
                titoloTextBox.Copy();
            }
            else if (txtFonti.Focused)
            {
                txtFonti.Copy();
            }
            else if (txtTag.Focused)
            {
                txtTag.Copy();
            }
        }
        private void cmdIncolla_Click(object sender, EventArgs e)
        {
            if (editor.Focused)
            {
                if (Clipboard.ContainsText())
                {
                    //Grosso problema nell'incolla.....
                    //Grosso problema nella cancellazione dall'ultimo carattere....
                    string testo = Clipboard.GetText().Replace("\r\n", "\r");
                    DataRowView view = (DataRowView)this.articoliBS.Current;
                    if (view != null)
                    {
                        articoliDS.ArticoliRow row = (articoliDS.ArticoliRow)view.Row;
                        try
                        {
                            CodeWorker.InsertString(testo);
                            row.BeginEdit();
                            row.Testo = CodeWorker.GetBBCode();
                            row.EndEdit();
                            editor.Paste(DataFormats.GetFormat("Text"));
                        }
                        catch (ApplicationException)
                        {

                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Errore sconosciuto", MessageBoxButtons.OK);
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Gli Appunti non contengono testo. E' possibile incollare solo testo.", "Errore", MessageBoxButtons.OK);
                }
            }
            else if (titoloTextBox.Focused)
            {
                titoloTextBox.Paste();
            }
            else if (txtFonti.Focused)
            {
                txtFonti.Paste();
            }
            else if (txtTag.Focused)
            {
                txtTag.Paste();
            }
        }
        private void cmdSelezionaTutto_Click(object sender, EventArgs e)
        {
            editor.Focus();
            editor.SelectAll();
        }
        #endregion

        #region Menù Formato
        private void cmdGrassetto_Click(object sender, EventArgs e)
        {
            CodeWorker.SetFormat(RichFormat.FormatType.Bold, true);
            UpdateDBAfterChangingFormat();
        }
        private void cmdSottolineato_Click(object sender, EventArgs e)
        {
            CodeWorker.SetFormat(RichFormat.FormatType.Underline, true);
            UpdateDBAfterChangingFormat();
        }
        private void cmdCorsivo_Click(object sender, EventArgs e)
        {
            CodeWorker.SetFormat(RichFormat.FormatType.Italic, true);
            UpdateDBAfterChangingFormat();
        }
        private void cmdBarrato_Click(object sender, EventArgs e)
        {
            CodeWorker.SetFormat(RichFormat.FormatType.Strikethrough, true);
            UpdateDBAfterChangingFormat();
        }
        private void cmdCodice_Click(object sender, EventArgs e)
        {
            CodeWorker.SetFormat(RichFormat.FormatType.Code, true);
            UpdateDBAfterChangingFormat();
        }
        private void cmdApice_Click(object sender, EventArgs e)
        {
            CodeWorker.SetFormat(RichFormat.FormatType.Superscript, true);
            UpdateDBAfterChangingFormat();
        }
        private void cmdElenco_Click(object sender, EventArgs e)
        {
            CodeWorker.SetFormat(RichFormat.FormatType.List, true);
            UpdateDBAfterChangingFormat();
        }

        //private void cmdElencoNumerato_Click(object sender, EventArgs e)
        //{
        //    CodeWorker.SetFormat(RichFormat.FormatType.NList, true);
        //    UpdateDBAfterChangingFormat();
        //}

        private void cmdCollegamento_Click(object sender, EventArgs e)
        {
            LinkBuilder lb = new LinkBuilder();
            DialogResult res = lb.ShowDialog();
            if (res == DialogResult.OK)
            {
                CodeWorker.SetFormatLink(lb.URL, lb.TargetLink, true);
                UpdateDBAfterChangingFormat();
            }
        }
        private void cmdFormatReset_Click(object sender, EventArgs e)
        {
            int pos = editor.SelectionStart + editor.SelectionLength;
            CodeWorker.RemoveFormat();
            UpdateDBAfterChangingFormat();
            editor.Focus();
            editor.Select(pos, 0);
        }
        private void UpdateDBAfterChangingFormat()
        {
            DataRowView view = (DataRowView)this.articoliBS.Current;
            articoliDS.ArticoliRow row = (articoliDS.ArticoliRow)view.Row;
            row.BeginEdit();
            row.Testo = CodeWorker.GetBBCode();
            row.EndEdit();
        }
        #endregion

        #region Menù Visualizza
        private void itemIcone_Click(object sender, EventArgs e)
        {
            itemIcone.Checked = !itemIcone.Checked;
            articoliNav.Visible = itemIcone.Checked;
        }
        private void itemTesta_Click(object sender, EventArgs e)
        {
            itemTesta.Checked = !itemTesta.Checked;
            pnlHeader.Visible = itemTesta.Checked;
        }
        private void itemStat_Click(object sender, EventArgs e)
        {
            itemStat.Checked = !itemStat.Checked;
            pnlStat.Visible = itemStat.Checked;
        }
        private void itemNote_Click(object sender, EventArgs e)
        {
            itemNote.Checked = !itemNote.Checked;
            MainStatus.Visible = itemNote.Checked;
        }
        private void itemEditorOnly_Click(object sender, EventArgs e)
        {
            itemEditorOnly.Checked = !itemEditorOnly.Checked;
            articoliNav.Visible = !itemEditorOnly.Checked;
            itemIcone.Checked = !itemEditorOnly.Checked;
            pnlHeader.Visible = !itemEditorOnly.Checked;
            itemTesta.Checked = !itemEditorOnly.Checked;
            pnlStat.Visible = !itemEditorOnly.Checked;
            itemStat.Checked = !itemEditorOnly.Checked;
            MainStatus.Visible = !itemEditorOnly.Checked;
            itemNote.Checked = !itemEditorOnly.Checked;
        }
        private void itemBBCode_Click(object sender, EventArgs e)
        {
            DataRowView view = (DataRowView)this.articoliBS.Current;
            if (view != null)
            {
                articoliDS.ArticoliRow row = (articoliDS.ArticoliRow)view.Row;
                BBCodeEditor editor = new BBCodeEditor(row.Testo);
                DialogResult rst = editor.ShowDialog();
                if (rst == DialogResult.OK)
                {
                    row.BeginEdit();
                    row.Testo = editor.TaggedText;
                    row.EndEdit();
                    UpdateRTF();
                }
            }

        }
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            string s = this.editor.Rtf;
            string s1 = this.editor.SelectedRtf;
            int start = this.editor.SelectionStart;
            int length = this.editor.SelectionLength;
            string text = String.Format("Testo:\r\n{0}\r\n\r\nSelected Rtf [{2},{3}]:\r\n{1}", s, s1, start, length);
            MessageBox.Show(text);
        }
        private void itemReport_Click(object sender, EventArgs e)
        {
            string conn = this.articoliTA.Connection.ConnectionString;
            Reporting rep = new Reporting(conn);
            rep.ShowDialog();
        }
        private void itemServer_Click(object sender, EventArgs e)
        {
            RemoteServer rs = new RemoteServer();
            rs.ShowDialog();
        }
        #endregion

        #region Menù Strumenti
        private void cmdVuotaDB_Click(object sender, EventArgs e)
        {
            string s = "Questa operazione cancellerà tutti i dati presenti sul database. Vuoi davvero procedere ?";
            DialogResult rst = MessageBox.Show(s, "Vuota database", MessageBoxButtons.YesNo);
            if (rst == DialogResult.Yes)
            {
                while (articoliBS.Count > 0)
                {
                    articoliBS.RemoveCurrent();
                }
                articoliBindingNavigatorSaveItem_Click(sender, e);
            }
        }
        private void cmdOpzioni_Click(object sender, EventArgs e)
        {
            Opzioni formOpzioni = new Opzioni();
            DialogResult rst = formOpzioni.ShowDialog();
            if (rst == DialogResult.OK)
            {
                PitEditor.Properties.Settings.Default.Save();
                LoadProperties();
            }
            else
            {
                PitEditor.Properties.Settings.Default.Reload();
            }
        }
        #endregion

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBox ab = new AboutBox();
            ab.ShowDialog();
        }

        #region Gestione Editor
        private void UpdateRTF()
        {
            DataRowView view = (DataRowView)this.articoliBS.Current;
            if (view != null)
            {
                articoliDS.ArticoliRow row = (articoliDS.ArticoliRow)view.Row;
                CodeWorker.Initialize(row.Testo);
                CodeWorker.UpdateRichTextBox();
                editor.Select(0, 0);
                UpdateLength();
                UpdatePos();
            }
        }
        private void editorBox_SelectionChanged(object sender, EventArgs e)
        {
            UpdatePos();
        }
        private void editor_TextChanged(object sender, EventArgs e)
        {
            UpdateLength();
        }
        private void UpdateLength()
        {
            string Testo = CodeWorker.GetBBCode();
            int charnumber = Testo.Length;
            lblCharsDB.Text = String.Format("{0:N0}", charnumber);
            string[] words = Testo.Split(new char[] { ' ', '\n' });
            int wordnumber = words.Where(c => c != "").Count();
            lblWordsDB.Text = String.Format("{0:N0}", wordnumber);
            float bytes = Convert.ToSingle(charnumber) / 1024;
            lblBytesDB.Text = String.Format("{0:N2}", bytes);
            articleSize.Position = bytes;
        }
        private void editor_KeyDown(object sender, KeyEventArgs e)
        {
            DataRowView view = (DataRowView)this.articoliBS.Current;
            if (view != null)
            {
                articoliDS.ArticoliRow row = (articoliDS.ArticoliRow)view.Row;
                try
                {
                    //Problemi maiuscolo-minuscolo
                    Keys key = e.KeyCode;
                    string keyDesc = key.ToString();
                    Keys mod = e.Modifiers;
                    bool Shift = e.Shift;
                    bool Control = e.Control;
                    bool Alt = e.Alt;
                    char ch = (char)e.KeyValue;

                    if (keyDesc == "Insert")            //TASTO INSERT
                    {
                        string message = String.Format("Tasto Insert. ANCORA NON GESTITO");
                        QuickInfo qi = new QuickInfo(editor, message);
                        e.SuppressKeyPress = true;
                    }
                    else if (keyDesc == "Delete")       //TASTO CANCEL
                    {
                        //Pressione di BackSpace
                        CodeWorker.HandleCancel();
                    }
                    else if (key == Keys.Back)          //TASTO DELETE
                    {
                        //Pressione di BackSpace
                        CodeWorker.HandleBackSpace();
                    }
                    row.BeginEdit();
                    row.Testo = CodeWorker.GetBBCode();
                    row.EndEdit();
                    CodeWorker.SpellCheckClear();
                }
                catch (ApplicationException)
                {
                    e.SuppressKeyPress = true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Errore sconosciuto", MessageBoxButtons.OK);
                    e.SuppressKeyPress = true;
                }
            }
        }
        private void editor_KeyPress(object sender, KeyPressEventArgs e)
        {
            DataRowView view = (DataRowView)this.articoliBS.Current;
            if (view != null)
            {
                articoliDS.ArticoliRow row = (articoliDS.ArticoliRow)view.Row;
                try
                {
                    char ch = e.KeyChar;
                    char[] RefusedChars = new char[] { '\b' };
                    if (!RefusedChars.Contains(ch))
                    {
                        CodeWorker.InsertChar(ch);
                        row.BeginEdit();
                        row.Testo = CodeWorker.GetBBCode();
                        row.EndEdit();
                    }
                }
                catch (ApplicationException)
                {
                    e.Handled = true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Errore sconosciuto", MessageBoxButtons.OK);
                    e.Handled = true;
                }
            }
        }
        private void editor_LinkClicked(object sender, LinkClickedEventArgs e)
        {
            string[] links = e.LinkText.Split(new char[] { '#' });
            if (links.Count() != 2)
            {
                throw new ApplicationException("Errore di formattazione del link.");
            }
            string link = links[1].Replace("\r", "");
            string testo = String.Format("Hai cliccato il link:\r\n{0}.\r\n\r\nDesideri visitarlo sul browser ?", link);
            DialogResult res = MessageBox.Show(testo, "Visita link", MessageBoxButtons.YesNo);
            if (res == DialogResult.Yes)
            {
                try
                {
                    System.Diagnostics.Process.Start(link);
                }
                catch
                {
                }
            }
        }
        private void btnAutoGetFonti_Click(object sender, EventArgs e)
        {
            DataRowView view = (DataRowView)this.articoliBS.Current;
            if (view != null)
            {
                articoliDS.ArticoliRow row = (articoliDS.ArticoliRow)view.Row;
                row.BeginEdit();
                string fonti = CodeWorker.GetLinks();
                row.Fonti = fonti.Length <= 1000 ? fonti : fonti.Substring(0, 1000);
                row.EndEdit();
            }
        }
        private void btnOpenWeb_Click(object sender, EventArgs e)
        {
            DataRowView view = (DataRowView)this.articoliBS.Current;
            if (view != null)
            {
                articoliDS.ArticoliRow row = (articoliDS.ArticoliRow)view.Row;
                string[] fonti = row.Fonti.Split(new char[] { '\r', '\n' });
                foreach (string s in fonti)
                {
                    if (s != "")
                        try
                        {
                            System.Diagnostics.Process.Start(s);
                        }
                        catch
                        {

                        }
                }
            }
        }
        private void btnRtf_Click(object sender, EventArgs e)
        {
            string s = editor.Rtf;
            MessageBox.Show(s);
        }
        #endregion

        #region Gestione Consigli di Agnese
        private void cmdSpellCheck_Click(object sender, EventArgs e)
        {
            int numb = CodeWorker.SpellCheck(titoloTextBox.Text);
            statusNote.Text = numb == 0 ?
                "Nessun errore rilevato." :
                String.Format("Rilevati {0} probabili errori.", numb);
        }
        #endregion
    }
}
